package com.phpxiu.app.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import com.phpxiu.app.adapter.UserSearchListAdapter;
import com.phpxiu.app.adapter.holder.SearchResultViewHolder;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.list.SearchResultContent;
import com.phpxiu.app.model.response.SearchModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.pulltorefresh.PullToRefreshListView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.ListEmptyView;
import com.phpxiu.app.view.custom.MEditText;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by WuJinZhou on 2016/6/6.
 */
public class UserSearch extends UIBase implements View.OnClickListener,
        PullToRefreshView.OnRefreshListener2<ListView>,
        AdapterView.OnItemClickListener,TextWatcher {
    public final static String TAG="UserSearch";
    private final static int HANDLE_REFRESH_COMPLETE=0x1;
    private List<SearchResultContent> results=new ArrayList<SearchResultContent>();
    private PullToRefreshListView ptrRefreshView;
    private ListView mListView;
    private ListEmptyView emptyView;
    private UserSearchListAdapter mAdapter;
    private int mOpera= HttpConfig.REQUEST_OPERA_INIT;
    private int pageSize=20;//每页取15条记录
    private int currentAllRecords=0;//当前列表刷新时获取的后台记录条数
    private int pageIndex=1;//下一页序号,页数从1开始计数
    private OKHttpParam param;
    private EditText mInput;
    private ImageButton clearInputBtn;
    private Button searchBtn;
    private boolean isRequest=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_search);
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        init();
    }
    /**
     * 初始化界面
     */
    private void init(){
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        mInput=(MEditText)findViewById(R.id.search_input_view);
        mInput.addTextChangedListener(this);
        clearInputBtn=(ImageButton)findViewById(R.id.clear_search_input_btn);
        clearInputBtn.setOnClickListener(this);
        searchBtn=(Button)findViewById(R.id.search_btn);
        searchBtn.setOnClickListener(this);
        ptrRefreshView=(PullToRefreshListView)findViewById(R.id.user_search_pull_refresh_list);
        mListView=ptrRefreshView.getRefreshableView();
        mListView.setOnItemClickListener(this);
        emptyView=new ListEmptyView(this);
        emptyView.loaded();
        emptyView.setMsg(getString(R.string.list_empty_title));
        mListView.setEmptyView(emptyView);
        mListView.setDivider(null);
        mAdapter=new UserSearchListAdapter(this,results);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(TextUtils.getTrimmedLength(s)>0){
                if(clearInputBtn.getVisibility()!=View.VISIBLE){
                    clearInputBtn.setVisibility(View.VISIBLE);
                }
            }else{
                if(clearInputBtn.getVisibility()==View.VISIBLE){
                    clearInputBtn.setVisibility(View.GONE);
                }
            }
    }

    @Override
    public void afterTextChanged(Editable s) {
        if(!TextUtils.isEmpty(s)){
            doSearch(HttpConfig.REQUEST_OPERA_INIT,false);
        }
    }

    /**
     * 查询
     */
    private void doSearch(int opera,boolean hideSoft){
        if(hideSoft){
            hideSoftInput(mInput);
        }
        if(isRequest){
            return;
        }
        if(TextUtils.isEmpty(mInput.getText())){
            //return;
        }
        mOpera=opera;
        if(param==null){
            param= OKHttpParam.builder(false);
            param.put("pageSize",pageSize);
        }
        param.put("pageIndex",1);
        if(mOpera==HttpConfig.REQUEST_OPERA_LOAD){
            param.put("pageIndex",pageIndex==1?2:pageIndex);
        }
        param.put("skey",mInput.getText().toString());
        isRequest=true;
        OKHttp.post(HttpConfig.API_USER_SEARCH, param.jsonParam(), TAG, new OKHttpUIHandler(SearchModel.class) {
            @Override
            public void onSuccess(Object model) {
                SearchModel m = (SearchModel) model;
                isRequest = false;
                if (ptrRefreshView != null) {
                    ptrRefreshView.onRefreshComplete();
                }
                KKYUtil.log("查询列表数据：" + m.getResponseStr());
                try {
                    if (mOpera == HttpConfig.REQUEST_OPERA_REFRESH || mOpera == HttpConfig.REQUEST_OPERA_INIT) {
                        currentAllRecords = m.getData().getTotalItem();
                        results.clear();
                        pageIndex = 1;
                    } else {
                        if (currentAllRecords > 0 && results.size() > 0 && results.size() < currentAllRecords) {
                            pageIndex++;
                        }
                    }
                    results.addAll(m.getData().getUserlist());
                    mAdapter.notifyDataSetChanged();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
                listEmpty(results.size() == 0);
                emptyView.setMsg(getString(R.string.list_empty_title));
            }

            @Override
            public void onErr(String errMsg) {
                listEmpty(results.size() == 0);
                isRequest = false;
                if (ptrRefreshView != null) {
                    ptrRefreshView.onRefreshComplete();
                }
                emptyView.setMsg(getString(R.string.list_empty_title));
            }
        });
    }

    @Override
    public void handleMsg(Message msg) {
        super.handleMsg(msg);
        switch (msg.what){
            case HANDLE_REFRESH_COMPLETE:
                if(ptrRefreshView!=null){
                    ptrRefreshView.onRefreshComplete();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            case R.id.search_btn:
                doSearch(HttpConfig.REQUEST_OPERA_INIT,true);
                break;
            case R.id.clear_search_input_btn:
                mInput.setText("");
                clearInputBtn.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(view.getTag()!=null&&view.getTag() instanceof SearchResultViewHolder){
            SearchResultContent a=((SearchResultViewHolder)view.getTag()).getContent();
            KKYUtil.log(TAG,"点击了："+a.getUid()+"@"+a.getNickname());
            Intent home=new Intent(this, UserHome.class);
            home.putExtra(UserHome.EXTRA_PARAM_KEY_UID,a.getUid());
            startActivity(home);
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshView<ListView> refreshView) {
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshView<ListView> refreshView) {
        if(results.size()!=0&&results.size()<currentAllRecords) {
            doSearch(HttpConfig.REQUEST_OPERA_LOAD,false);
        }else{
            handler.sendEmptyMessage(HANDLE_REFRESH_COMPLETE);
        }
    }

    /**
     * 关闭键盘
     */
    protected void hideSoftInput(View input) {
        if(input == null) return;
        InputMethodManager imm = (InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(input.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 空列表,不加载更多
     */
    public void listEmpty(boolean isEmpty){
        if (ptrRefreshView != null) {
            if(isEmpty) {
                ptrRefreshView.setMode(PullToRefreshView.Mode.DISABLED);
            }else{
                ptrRefreshView.setMode(PullToRefreshView.Mode.PULL_FROM_END);
            }
        }
    }
}
